package com.stock.publiclib;


import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.stock.publiclib.model.UserService;
import com.stock.publiclib.network.NetWorkCenter;
import com.stock.publiclib.utils.StringUtil;


/**
 * Created by ljgsonx on 2016/1/15.
 */
public abstract class LibCenter {

    private final static String TAG = "LibCenter--->";

    private static RequestQueue mRequestQueue;

    private static UserService mUserService;

    protected static Context mContext;

    protected static String commondb_name;
    protected static int mVersion;

    private static BitmapCache mBitmapCache;

    private static RequestQueue getQueue(){
        if(null == mRequestQueue){
            mRequestQueue = NetWorkCenter.getQueue(mContext);
        }
        return mRequestQueue;
    }

    public <T>void doNetWorkReq(Request<T> request){
        if(mContext != null){
            getQueue().add(request);
        }else {
            Log.d(TAG, "未初始化上下文!");
        }
    }

    public static void cancelReq(String tag){
        if(tag != null) {
            getQueue().cancelAll(tag);
        }
    }

    public ImageLoader getDefaultImageLoader(){
        if(mBitmapCache == null) mBitmapCache = new BitmapCache();
        return new ImageLoader(getQueue(), mBitmapCache);
    }

    public UserService getUserService() {
        if(StringUtil.isBlank(commondb_name) || mVersion == 0){
            Log.d(TAG, "未初始化存储参数!");
            return null;
        }else{
            if(null == mUserService){
                mUserService = new UserService(mContext, commondb_name, mVersion);
            }
            return mUserService;
        }
    }

    class BitmapCache implements ImageLoader.ImageCache {

        private LruCache<String, Bitmap> mCache;

        public BitmapCache() {
            int maxSize = 2 * 1024 * 1024;
            mCache = new LruCache<String, Bitmap>(maxSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            };
        }

        @Override
        public Bitmap getBitmap(String url) {
            return mCache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            mCache.put(url, bitmap);
        }

    }
}
